// lib/services/api_response.dart
import 'dart:convert'; // Add this import

class ApiResponse<T> {
  final int code;
  final String message;
  final T? data;
  final bool success;

  // 添加 count 和 current 字段
  final int? count;
  final int? current;

  ApiResponse({
    required this.code,
    required this.message,
    this.data,
    required this.success,
    this.count, // 构造函数也要添加
    this.current, // 构造函数也要添加
  });

  factory ApiResponse.fromJson(
    Map<String, dynamic> json,
    T? Function(dynamic)? fromJson,
  ) {
    final code = json['code'] as int? ?? -1;
    final message =
        json['message'] as String? ?? (json['msg'] as String? ?? '未知错误');
    final success = code == 200;

    T? parsedData;
    if (json.containsKey('data') && fromJson != null) {
      try {
        // fromJson 将接收 json['data'] 的值
        parsedData = fromJson(json['data']);
      } catch (e) {
        print("解析数据失败: $e");
        parsedData = null;
      }
    } else if (json.containsKey('data') && fromJson == null) {
      parsedData = json['data'] as T?;
    }

    // 解析 count 和 current
    final count = json['count'] as int?;
    final current = json['current'] as int?;

    return ApiResponse(
      code: code,
      message: message,
      data: parsedData,
      success: success,
      count: count,
      current: current,
    );
  }

  factory ApiResponse.success(
    T data, {
    String message = '成功',
    int? count,
    int? current,
  }) {
    return ApiResponse(
      code: 200,
      message: message,
      data: data,
      success: true,
      count: count,
      current: current,
    );
  }

  factory ApiResponse.failure({int code = -1, String message = '请求失败'}) {
    return ApiResponse(code: code, message: message, success: false);
  }
}
